<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.1.E.7.files</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.1.E.7.files.html" rel="bookmark"
           title="Permalink to Part.1.E.7.files">Part.1.E.7.files</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>文件</h1>
<p>我们需要处理的数据，一定是很多，所以才必须由计算机帮我们处理 —— 大量的数据保存、读取、写入，需要的就是文件（Files）。在这一章里，我们只介绍最简单的文本文件。</p>
<h2>创建文件</h2>
<p>创建一个文件，最简单的方式就是用 Python 的内建函数 <code>open()</code>。</p>
<p><code>open()</code> 函数的<a href="https://docs.python.org/3/library/functions.html#open">官方文档</a>很长，以下是个简化版：</p>
<blockquote>
<p><code>open(file, mode='r')</code></p>
</blockquote>
<p>第二个参数，<code>mode</code>，默认值是 <code>'r'</code>，可用的 <code>mode</code> 有以下几种：</p>
<table>
<thead>
<tr>
<th>参数字符</th>
<th>意义</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>'r'</code></td>
<td>只读模式</td>
</tr>
<tr>
<td><code>'w'</code></td>
<td>写入模式（重建）</td>
</tr>
<tr>
<td><code>'x'</code></td>
<td>排他模式 —— 如果文件已存在则打开失败</td>
</tr>
<tr>
<td><code>'a'</code></td>
<td>追加模式 —— 在已有文件末尾追加</td>
</tr>
<tr>
<td><code>'b'</code></td>
<td>二进制文件模式</td>
</tr>
<tr>
<td><code>'t'</code></td>
<td>文本文件模式（默认）</td>
</tr>
<tr>
<td><code>'+'</code></td>
<td>读写模式（更新）</td>
</tr>
</tbody>
</table>
<p>创建一个新文件，用这样一个语句就可以：</p>
<div class="highlight"><pre><span></span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>&lt;_io.TextIOWrapper name=&#39;/tmp/test-file.txt&#39; mode=&#39;w&#39; encoding=&#39;UTF-8&#39;&gt;
</pre></div>


<p>当然，更多的时候，我们会把这个函数的返回值，一个所谓的 <a href="https://docs.python.org/3/glossary.html#term-file-object">file object</a>，保存到一个变量中，以便后面调用这个 file object 的各种 Methods，比如获取文件名 <code>file.name</code>，比如关闭文件 <code>file.close()</code>：</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>/tmp/test-file.txt
</pre></div>


<h2>删除文件</h2>
<p>删除文件，就得调用 <code>os</code> 模块了。删除文件之前，要先确认文件是否存在，否则删除命令会失败。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file1.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="c1">#关闭文件，否则无法删除文件</span>
<span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">):</span>
    <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{f.name} deleted.&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{f.name} does not exist.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>/tmp/test-file1.txt
/tmp/test-file1.txt deleted.
</pre></div>


<h2>读写文件</h2>
<p>创建文件之后，我们可以用 <code>f.write()</code> 把数据写入文件，也可以用 <code>f.read()</code> 读取文件。</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
third line
</pre></div>


<p>文件有很多行的时候，我们可以用 <code>file.readline()</code> 操作，这个 Method 每次调用，都会返回文件中的新一行。</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>    <span class="c1"># 返回的是 &#39;first line\n&#39;</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>    <span class="c1"># 返回的是 &#39;second line\n&#39;</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
</pre></div>


<p><strong>注意</strong>，返回结果好像跟你想的不太一样。这时候，之前见过的 <code>str.strip()</code> 就派上用场了：</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>    <span class="c1"># 返回的是 &#39;first line&#39;，&#39;\n&#39; 被去掉了……</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>    <span class="c1"># 返回的是 &#39;second line&#39;，&#39;\n&#39; 被去掉了……</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
</pre></div>


<p>与之相对的，我们可以使用 <code>file.readlines()</code> 这个 Method，将文件作为一个列表返回，列表中的每个元素对应着文件中的每一行：</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>    <span class="c1"># 返回的是一个列表，注意，readlines，最后的 &#39;s&#39;</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;first line\n&#39;, &#39;second line\n&#39;, &#39;third line\n&#39;]
</pre></div>


<p>既然返回的是列表，那么就可以被迭代，逐一访问每一行：</p>
<div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
third line
</pre></div>


<p>与之相对的，我们也可以用 <code>file.writelines()</code> 把一个列表写入到一个文件中，按索引顺序（从 0 开始）逐行写入列表的对应元素：：</p>
<div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;second line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">writelines</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
third line
</pre></div>


<h2>with 语句块</h2>
<p>针对文件操作，Python 有个另外的语句块写法，更便于阅读：</p>
<div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="o">...</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
    <span class="o">...</span>
</pre></div>


<p>这样，就可以把针对当前以特定模式打开的某个文件的各种操作都写入同一个语句块了：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;first line</span><span class="se">\n</span><span class="s1">second line</span><span class="se">\n</span><span class="s1">third line</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/tmp/test-file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
        <span class="k">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>

<span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">):</span>
    <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{f.name} deleted.&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{f.name} does not exist.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>first line
second line
third line
test-file.txt deleted.
</pre></div>


<p>另外，用 <code>with</code> 语句块的另外一个附加好处就是不用写 <code>file.close()</code> 了……</p>
<h2>另一个完整的程序</h2>
<p>若干年前，我在写某本书的时候，需要一个例子 —— 用来说明 “<strong>即便是结论正确，论证过程乱七八糟也不行！</strong>”</p>
<p>作者就是这样，主要任务之一就是给论点找例子找论据。找得到不仅<em>恰当</em>且又<em>精彩</em>的例子和论据的，就是好作者。后面这个 “<em>精彩</em>” 二字要耗费很多时间精力，因为它意味着说 “要找到<em>很多</em>例子而后在里面选出<em>最精彩</em>的那个！” —— 根本不像很多人以为的那样，是所谓的 “信手拈来”。</p>
<p>找了很多例子都不满意…… 终于有一天，我看到这么个说法：</p>
<blockquote>
<p>如果把字母 <code>a</code> 计为 <code>1</code>、<code>b</code> 计为 <code>2</code>、<code>c</code> 计为 <code>3</code> …… <code>z</code> 计为 <code>26</code>，那么：</p>
<ul>
<li>knowledge = 96</li>
<li>hardwork = 98</li>
<li>attitude = 100</li>
</ul>
<p>所以结论是：</p>
<ul>
<li>知识（<em>knowledge</em>）与勤奋（<em>hardwork</em>）固然都很重要；</li>
<li>但是，决定成败的却是态度（<strong>attitude</strong>）！</li>
</ul>
</blockquote>
<p>结论虽然有道理 —— 可这论证过程实在是太过分了罢……</p>
<p>我很高兴，觉得这就是个<em>好例子</em>！并且，加工一下，会让读者觉得很精彩 —— 如果能找到一些按照同样的计算方式能得到 100 的单词，并且还是那种一看就是 “反例” 的单词……</p>
<p>凭直觉，英文单词几十万，如此这般等于 100 的单词岂不是数不胜数？并且，一定会有很多负面意义的单词如此计算也等于 100 罢？然而，这种事情凭直觉是不够的，手工计算又会被累死…… 于是，面对如此荒谬的论证过程，我们竟然 “无话可说”。</p>
<p>幸亏我是会写程序的人。所以，不会 “干着急没办法”，我有能力让计算机帮我把活干了。</p>
<p>很快就搞定了，找到很多很多个如此计算加起来等于 100 的英文单词，其中包括：</p>
<blockquote>
<ul>
<li>connivance（纵容）</li>
<li>coyness（羞怯）</li>
<li>flurry（慌张）</li>
<li>impotence（阳痿）</li>
<li>stress（压力）</li>
<li>tuppence（微不足道的东西）</li>
<li>……</li>
</ul>
</blockquote>
<p>所以，决定成败的可以是 “慌张”（flurry），甚至是 “阳痿”（impotence）？这不明显是胡说八道嘛！</p>
<p>—— 精彩例子制作完毕，我把它放进了书里。</p>
<p>那，具体的过程是什么样的呢？</p>
<p>首先我得找到一个英文单词列表，很全的那种。这事用不着写程序，Google 一下就可以了。我搜索的关键字是 “<a href="https://www.google.com/search?q=english+word+list">english word list</a>”，很直观吧？然后就找到一个：<a href="https://github.com/dwyl/english-words">https://github.com/dwyl/english-words</a>；这个链接里有一个 <a href="https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt">words-alpha.txt</a> 文件，其中包含接近 37,0101 个单词，应该够用了！下载下来用程序处理就可以了！</p>
<p>因为文件里每行一个单词，所以，就让程序打开文件，将文件读入一个列表，而后迭代这个列表，逐一计算那个单词每个字母所代表的数字，并加起来看看是否等于 100？如果是，就将它们输出到屏幕…… 好像不是很难。</p>
<div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;words_alpha.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="nb">file</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
        <span class="k">pass</span> <span class="c1"># 先用 pass 占个位，一会儿再写计算过程</span>
</pre></div>


<p>按照上面那说法，把 <code>a</code> 记为 <code>1</code>，直至把 <code>z</code> 记为 <code>26</code>，这事并不难，因为有 <code>ord()</code> 函数啊 —— 这个函数返回字符的 Unicode 编码：<code>ord('a')</code> 的值是 <code>97</code>，那按上面的说法，用 <code>ord('a') - 96</code> 就相当于得到了 <code>1</code> 这个数值…… 而 <code>ord('z') - 96</code> 就会得到 <code>26</code> 这个数值。</p>
<div class="highlight"><pre><span></span><span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>97
</pre></div>


<p>那么，计算 <code>'knowledge'</code> 这个字符串的代码很简单：</p>
<div class="highlight"><pre><span></span><span class="n">word</span> <span class="o">=</span> <span class="s1">&#39;knowledge&#39;</span>
<span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
    <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
<span class="k">print</span><span class="p">(</span><span class="nb">sum</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>96
</pre></div>


<p>果然，得到的数值等于 <code>96</code> —— 不错。把它写成一个函数罢：<code>sum_of_word(word)</code>:</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
    <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
        <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
    <span class="k">return</span> <span class="nb">sum</span>

<span class="n">sum_of_word</span><span class="p">(</span><span class="s1">&#39;attitude&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>100
</pre></div>


<p>那让程序就算把几十万行都算一遍也好像很简单了：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
    <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
        <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
    <span class="k">return</span> <span class="nb">sum</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;words_alpha.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="nb">file</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
        <span class="k">if</span> <span class="n">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="o">==</span> <span class="mi">100</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>abstrusenesses
acupuncturist
adenochondrosarcoma
...
worshipability
zeuctocoelomatic
zygapophysis
</pre></div>


<p>嗯？怎么输出结果跟想得不一样？找到的词怎么都 “奇形怪状” 的…… 而且，输出结果中也没有 <code>attitude</code> 这个词。</p>
<p>插入个中止语句，<code>break</code>，把找到的第一个词中的每个字符和它所对应的值都拿出来看看？</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
    <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
        <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
    <span class="k">return</span> <span class="nb">sum</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;words_alpha.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="nb">file</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
        <span class="k">if</span> <span class="n">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="o">==</span> <span class="mi">100</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
            <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>        <span class="c1"># 把字母和值都打出来，看看对不对？</span>
                <span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span><span class="p">)</span>
            <span class="k">break</span>                 <span class="c1"># 找到一个之后就停下来。</span>
</pre></div>


<div class="highlight"><pre><span></span>abstrusenesses

a 1
b 2
s 19
t 20
r 18
u 21
s 19
e 5
n 14
e 5
s 19
s 19
e 5
s 19

 -86
</pre></div>


<p>怎么有个 <code>-86</code>？！仔细看看输出结果，看到每一行之间都被插入了一个空行，想到应该是从文件里读出的行中，包含 <code>\n</code> 这种换行符…… 如果是那样的话，那么 <code>ord('\n') -96</code> 返回的结果是 <code>-86</code> 呢，怪不得找到的词都 “奇形怪状” 的……</p>
<div class="highlight"><pre><span></span><span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span> <span class="o">-</span><span class="mi">96</span>
</pre></div>


<div class="highlight"><pre><span></span>-86
</pre></div>


<p>改进一下呗 —— 倒也简单，在计算前把读入字符串前后的空白字符都给删掉就好了，用 <code>str.strip()</code> 就可以了：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
    <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
        <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
    <span class="k">return</span> <span class="nb">sum</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;words_alpha.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="nb">file</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
        <span class="k">if</span> <span class="n">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span> <span class="o">==</span> <span class="mi">100</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>abactinally
abatements
abbreviatable
...
zithern
zoogleas
zorgite
</pre></div>


<p>如果想把符合条件的词保存到一个文件 <code>results.txt</code> 里的话，那么：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
    <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">word</span><span class="p">:</span>
        <span class="nb">sum</span> <span class="o">+=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="o">-</span> <span class="mi">96</span>
    <span class="k">return</span> <span class="nb">sum</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;results.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">result</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;words_alpha.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="nb">file</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">sum_of_word</span><span class="p">(</span><span class="n">word</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span> <span class="o">==</span> <span class="mi">100</span><span class="p">:</span>
                <span class="n">result</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
</pre></div>


<p>竟然这么简单就搞定了？！</p>
<p>这 10 行的代码，在几秒钟内从 370,101 个英文单词中找到 3,771 个如此计算等于 100 的词汇。</p>
<p>喝着咖啡翻一翻 <code>results.txt</code>，很快就找到了那些用来做反例格外恰当的词汇。</p>
<p>真无法想象当年的自己若是不懂编程的话现在会是什么样子……</p>
<h2>总结</h2>
<p>这一章我们介绍了文本文件的基本操作：</p>
<blockquote>
<ul>
<li>打开文件，直接用内建函数，<code>open()</code>，基本模式有 <code>r</code> 和 <code>w</code>；</li>
<li>删除文件，得调用 <code>os</code> 模块，使用 <code>os.remove()</code>，删除文件前最好确认文件确实存在……</li>
<li>读写文件分别有 <code>file.read()</code>、<code>file.write()</code>、<code>file.readline()</code>、<code>file.readlines()</code>、<code>file.writelines()</code>；</li>
<li>可以用 <code>with</code> 把相关操作都放入同一个语句块……</li>
</ul>
</blockquote>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>